<template>
<div>
<!-- 表格组件 -->
   <el-table
    :data="RloesList"
    border
    style="width: 100%">
    <!-- 展开列 -->
    <el-table-column type="expand">
      <template slot-scope="scope">
        <el-row :class="['bdbottom',i1 === 0 ? 'bdtop': '','vcenter']" v-for="(item1,i1) in scope.row.children" :key="item1.id">
          <!-- 渲染一级权限 -->
          <el-col :span="5">
            <el-tag closable>{{ item1.authName }}</el-tag>
            <i class="el-icon-caret-right"></i>
          </el-col>
          <!-- 渲染二级和三级权限 -->
          <el-col :span="19">
            <el-row :class="[i2 === 0 ? '': 'bdtop','vcenter']" v-for="(item2,i2) in item1.children" :key="item2.id">
              <el-col :span="6">
                <el-tag type="success" closable>{{ item2.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="18">
                <el-tag type="warning" v-for="item3 in item2.children" :key="item3.id" closable @close="removeRightById(item3.id,scope.row)">{{ item3.authName }}</el-tag>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </template>
    </el-table-column>
    <el-table-column type="index"></el-table-column>
    <el-table-column label="角色名称" prop="roleName"></el-table-column>
    <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
    <el-table-column label="操作" width="300px">
      <template slot-scope="scope">
         <el-button type="primary" icon="el-icon-edit" size="small">编辑</el-button>
         <el-button type="danger" icon="el-icon-delete" size="small">删除</el-button>
         <el-tooltip content="分配权限" placement="top" :enterable="false">
          <el-button type="warning" icon="el-icon-setting" size="small" @click="SetRightDialog(scope.row)">分配权限</el-button>
        </el-tooltip>
      </template>
    </el-table-column>
  </el-table>
  <!-- 分配权限的对话框 -->
  <el-dialog title="分配权限" :visible.sync="DialogRightVisible" width="50%" @close="setRightDialogClosed">
            <el-tree
              ref="treeRef"
              :data="RightsList"
              show-checkbox
              node-key="id"
              :default-expand-all="true"
              :default-checked-keys="defKeys"
              :props="TreeProps">
            </el-tree>
            <div slot="footer" class="dialog-footer">
                 <el-button @click="DialogRightVisible = false">取 消</el-button>
                 <el-button type="primary" @click="allotRights">确 定</el-button>
            </div>
    </el-dialog>
</div>
</template>
<script>
export default {
  props: {
    RloesList: {
      type: Array,
      default () {}
    }
  },
  data () {
    return {
      // 控制分配权限框的显示和隐藏
      DialogRightVisible: false,
      // 所有权限的数据
      RightsList: {},
      // 树形控件的绑定对象
      TreeProps: {
        children: 'children',
        label: 'authName'
      },
      // 默认选中的节点Id值数组
      defKeys: [],
      RoleId: ''
    }
  },
  methods: {
    // 点击为角色分配权限
    async allotRights () {
      // 将当前选中和半选中的权限ID都写入数组
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      // 将数组按 ','分割成字符串
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.RoleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) return this.$message.error('修改失败')
      this.$message.success('权限分配成功')
      // 向父组件传一个方法重新渲染页面
      this.$emit('NewRloesList')
      // 关闭分配权限的对话框
      this.DialogRightVisible = false
    },
    // 分配权限对话框关闭时清空defKeys
    setRightDialogClosed () {
      this.defKeys = []
    },
    // 显示分配权限的对话框
    async SetRightDialog (rloe) {
      this.RoleId = rloe.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('数据获取失败')
      // 把获取到的权限数据保存到 data中
      this.RightsList = res.data
      // 递归获取三级节点的Id
      this.getLeafKeys(rloe, this.defKeys)
      this.DialogRightVisible = true
    },
    // 通过递归的形式，获取角色下所有三级权限的id，并保存到 defKeys 数组中
    getLeafKeys (node, arr) {
      if (!node.children) return arr.push(node.id)
      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    // 根据ID删除对应的权限
    async removeRightById (RightId, rloes) {
      const rloesId = rloes.id
      // 弹框提示用户是否要删除
      const confirmResult = await this.$confirm('是否确认删除！', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') return this.$message.info('取消了删除')
      const { data: res } = await this.$http.delete(`roles/${rloesId}/rights/${RightId}`)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      // 将返回的新数据给页面
      rloes.children = res.data
    }
  }
}
</script>
<style lang="scss" scoped>
  .el-tag{
    margin:7px
  }
  .bdtop{
    border-top: 1px solid #eee;
  }
  .bdbottom{
    border-bottom: 1px solid #eee;
  }
  .vcenter{
    display: flex;
    align-items: center;
  }
</style>
